import Foundation
import Combine

enum APIError: Error {
    case invalidURL
    case invalidResponse
    case networkError(Error)
    case decodingError(Error)
    case apiError(String)
    case noApiKey
}

class APIService {
    // 单例模式
    static let shared = APIService()
    
    private init() {}
    
    // 发送聊天请求到OpenAI
    func sendOpenAIRequest(messages: [ChatMessage], config: AIModelConfig) -> AnyPublisher<String, APIError> {
        guard let apiKey = KeychainService.getAPIKey(service: "openai"), !apiKey.isEmpty else {
            return Fail(error: APIError.noApiKey).eraseToAnyPublisher()
        }
        
        // 构建请求URL
        guard let url = URL(string: "https://api.openai.com/v1/chat/completions") else {
            return Fail(error: APIError.invalidURL).eraseToAnyPublisher()
        }
        
        // 准备请求消息
        let requestMessages = messages.map { message -> [String: String] in
            return [
                "role": message.role.rawValue,
                "content": message.content
            ]
        }
        
        // 构建请求体
        let requestBody: [String: Any] = [
            "model": config.modelType.rawValue,
            "messages": requestMessages,
            "temperature": config.temperature,
            "max_tokens": config.maxTokens
        ]
        
        // 序列化请求体
        guard let jsonData = try? JSONSerialization.data(withJSONObject: requestBody) else {
            return Fail(error: APIError.invalidURL).eraseToAnyPublisher()
        }
        
        // 创建请求
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
        
        // 发送请求
        return URLSession.shared.dataTaskPublisher(for: request)
            .mapError { APIError.networkError($0) }
            .flatMap { data, response -> AnyPublisher<String, APIError> in
                guard let httpResponse = response as? HTTPURLResponse else {
                    return Fail(error: APIError.invalidResponse).eraseToAnyPublisher()
                }
                
                guard 200...299 ~= httpResponse.statusCode else {
                    let errorMessage = String(data: data, encoding: .utf8) ?? "Unknown error"
                    return Fail(error: APIError.apiError("Status code: \(httpResponse.statusCode), Error: \(errorMessage)")).eraseToAnyPublisher()
                }
                
                do {
                    if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                       let choices = json["choices"] as? [[String: Any]],
                       let firstChoice = choices.first,
                       let message = firstChoice["message"] as? [String: Any],
                       let content = message["content"] as? String {
                        return Just(content)
                            .setFailureType(to: APIError.self)
                            .eraseToAnyPublisher()
                    } else {
                        return Fail(error: APIError.apiError("Invalid response format")).eraseToAnyPublisher()
                    }
                } catch {
                    return Fail(error: APIError.decodingError(error)).eraseToAnyPublisher()
                }
            }
            .eraseToAnyPublisher()
    }
    
    // 发送聊天请求到Anthropic
    func sendAnthropicRequest(messages: [ChatMessage], config: AIModelConfig) -> AnyPublisher<String, APIError> {
        guard let apiKey = KeychainService.getAPIKey(service: "anthropic"), !apiKey.isEmpty else {
            return Fail(error: APIError.noApiKey).eraseToAnyPublisher()
        }
        
        // 构建请求URL
        guard let url = URL(string: "https://api.anthropic.com/v1/messages") else {
            return Fail(error: APIError.invalidURL).eraseToAnyPublisher()
        }
        
        // 准备请求消息
        var requestMessages: [[String: String]] = []
        
        for message in messages {
            // Anthropic API 不支持 system 角色，需要转换
            if message.role == .system {
                requestMessages.append([
                    "role": "user",
                    "content": message.content
                ])
                requestMessages.append([
                    "role": "assistant",
                    "content": "我明白了，我会按照你的指示行动。"
                ])
            } else {
                requestMessages.append([
                    "role": message.role == .assistant ? "assistant" : "user",
                    "content": message.content
                ])
            }
        }
        
        // 构建请求体
        let requestBody: [String: Any] = [
            "model": config.modelType.rawValue,
            "messages": requestMessages,
            "temperature": config.temperature,
            "max_tokens": config.maxTokens
        ]
        
        // 序列化请求体
        guard let jsonData = try? JSONSerialization.data(withJSONObject: requestBody) else {
            return Fail(error: APIError.invalidURL).eraseToAnyPublisher()
        }
        
        // 创建请求
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("anthropic-version: 2023-06-01", forHTTPHeaderField: "anthropic-version")
        request.addValue("\(apiKey)", forHTTPHeaderField: "x-api-key")
        
        // 发送请求
        return URLSession.shared.dataTaskPublisher(for: request)
            .mapError { APIError.networkError($0) }
            .flatMap { data, response -> AnyPublisher<String, APIError> in
                guard let httpResponse = response as? HTTPURLResponse else {
                    return Fail(error: APIError.invalidResponse).eraseToAnyPublisher()
                }
                
                guard 200...299 ~= httpResponse.statusCode else {
                    let errorMessage = String(data: data, encoding: .utf8) ?? "Unknown error"
                    return Fail(error: APIError.apiError("Status code: \(httpResponse.statusCode), Error: \(errorMessage)")).eraseToAnyPublisher()
                }
                
                do {
                    if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                       let content = json["content"] as? [[String: Any]],
                       let firstContent = content.first,
                       let text = firstContent["text"] as? String {
                        return Just(text)
                            .setFailureType(to: APIError.self)
                            .eraseToAnyPublisher()
                    } else {
                        return Fail(error: APIError.apiError("Invalid response format")).eraseToAnyPublisher()
                    }
                } catch {
                    return Fail(error: APIError.decodingError(error)).eraseToAnyPublisher()
                }
            }
            .eraseToAnyPublisher()
    }
    
    // 根据提供商选择合适的API请求方法
    func sendChatRequest(messages: [ChatMessage], config: AIModelConfig) -> AnyPublisher<String, APIError> {
        switch config.provider {
        case .openAI:
            return sendOpenAIRequest(messages: messages, config: config)
        case .anthropic:
            return sendAnthropicRequest(messages: messages, config: config)
        }
    }
} 